﻿/******************************
 * MD5加密解密的封装
 * @Author wuzhang
 * 2014/12/4
 *****************************/
using UnityEngine;
using System.Text;
using System.Collections;
using System.Security.Cryptography;


public class Encryption : MonoBehaviour 
{
	public string strkeyValue;
	// Use this for initialization
	void Start () 
	{
		//加密和解密采用相同的key,可以任意数字，但是必须为32位
		strkeyValue = "12345678901234567890198915689039";
	}

	public void encryptionClick()
	{
		string inputText = "HelloWorld";
		string strEncryption=encryptionContent(inputText, strkeyValue);
		Debug.Log("加密:"+strEncryption);
		Debug.Log("解密:"+decipheringContent(strEncryption,strkeyValue));
	}

	// Update is called once per frame
	void Update () 
	{
	
	}
	/// <summary>
	/// 内容加密
	/// </summary>
	/// <param name="ContentInfo">要加密内容</param>
	/// <param name="strkey">key值</param>
	/// <returns></returns>
	public string encryptionContent(string ContentInfo,string strkey)
	{
		byte[] keyArray = UTF8Encoding.UTF8.GetBytes(strkey);
		RijndaelManaged encryption = new RijndaelManaged();
		encryption.Key = keyArray;
		encryption.Mode = CipherMode.ECB;
		encryption.Padding = PaddingMode.PKCS7;
		ICryptoTransform cTransform = encryption.CreateEncryptor();
		byte[] _EncryptArray = UTF8Encoding.UTF8.GetBytes(ContentInfo);
		byte[] resultArray = cTransform.TransformFinalBlock(_EncryptArray, 0, _EncryptArray.Length);
		return System.Convert.ToBase64String(resultArray, 0, resultArray.Length);
	}

	/// <summary>
	/// 内容解密
	/// </summary>
	/// <param name="encryptionContent">被加密内容</param>
	/// <param name="strkey">key值</param>
	/// <returns></returns>
	public string decipheringContent(string encryptionContent,string strkey)
	{
		byte[] keyArray = UTF8Encoding.UTF8.GetBytes(strkey);
		RijndaelManaged decipher = new RijndaelManaged();
		decipher.Key = keyArray;
		decipher.Mode = CipherMode.ECB;
		decipher.Padding = PaddingMode.PKCS7;
		ICryptoTransform cTransform = decipher.CreateDecryptor();
		byte[] _EncryptArray =System.Convert.FromBase64String(encryptionContent);
		byte[] resultArray = cTransform.TransformFinalBlock(_EncryptArray, 0, _EncryptArray.Length);
		return UTF8Encoding.UTF8.GetString(resultArray);
	}


}
